<?php

namespace Tbf\Bundle\DatabaseBundle\ListQuery;

use Tbf\Bundle\SerializerBundle\Serializer;

class ListQueryHandler
{
    protected $orm_query_builder_adapter;
    protected $qb;
    /** @var \Tbf\Bundle\DatabaseBundle\ListQuery\ListQuery */
    protected $list_query;
    /** @var \Tbf\Bundle\SerializerBundle\Serializer */
    protected $serializer;

    public function __construct(Serializer $serializer=null)
    {
        $this->serializer = $serializer;
    }

    public function fromOrmQueryBuilder($qb)
    {
        $this->qb = $qb;

        return $this;
    }
    public function fromListQuery(ListQuery $list_query){
        $this->list_query = $list_query;
        return $this;
    }
    public function fromListQueryArray($list_query)
    {
        $this->list_query = $this->serializer->newFromArray('Tbf\Bundle\DatabaseBundle\ListQuery\ListQuery', $list_query);

        return $this;
    }
    public function getListQuery()
    {
        return $this->list_query;
    }
    public function fromConditionalExpressArray($conditional_express)
    {
        $this->list_query = $this->serializer->newFromArray('Tbf\Bundle\DatabaseBundle\ListQuery\ListQuery',
            array('where' => $conditional_express)
        );
        $this->list_query->setIsPageResult(false);

        return $this;
    }

    public function getPageArrayResult()
    {
        $result = $this->getPageResult();

        return $this->serializer->toArray($result);
    }
    public function getPageResult()
    {
        $result = $this->getResult();
        $total = $this->getTotal();
        $total_page = ceil($this->getTotal() / $this->list_query->getPageSize());
        return array(
            'data' => $result,
            'total' => $total,
            'total_page'=>$total_page
        );
    }
    public function getResult()
    {
        return $this->getQueryBuilder()->getQuery()->getResult();
    }

    public function getQueryBuilder()
    {
        $adapter = new DoctrineOrmQueryBuilderAdapter($this->list_query);

        return $adapter->loadSelectQuery(clone $this->qb);
    }

    public function getTotalQueryBuilder()
    {
        $adapter = new DoctrineOrmQueryBuilderAdapter($this->list_query);

        return $adapter->loadCountQuery(clone $this->qb);
    }

    public function getTotal()
    {
        $count = $this->getTotalQueryBuilder()->getQuery()->getArrayResult();
        if (empty($count)) {
            return 0;
        }
        $count = array_pop($count);
        $count = array_pop($count);

        return $count;
    }
}
